<template>
  <div class="container">
    <div class="cardBox" style="width: 100%; height: 100%">
      <v-stage :config="configKonva">
        <v-layer>
          <v-circle
            @touchstart="selectItem(piece)"
            @mousedown="selectItem(piece)"
            v-for="(piece, i) in circleData"
            :key="i"
            :config="piece"
          ></v-circle>
          <v-line v-for="(s, i) in segment" :key="i" :config="s"></v-line>
          <v-text
            v-for="(text, i) in TextDatas"
            :key="i"
            :config="text"
          ></v-text>
        </v-layer>
      </v-stage>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref, inject, watch, onMounted, ComputedRef } from 'vue';
import {ISegment,ITextDatas,ICircle, createStore } from '../store/app';
import { message } from 'ant-design-vue';
interface preset {
  itemWidth: number;
  itemHeight: number;
  columns: number;
  rows: number;
  XGap: number;
  YGap: number;
  [key: string]: any;
}


export default defineComponent({
  props: {},
  setup(props) {
    const configKonva = ref({
      width: 900,
      height: 720,
    });
    const store = inject('store') as ReturnType<ReturnType<typeof createStore>>;
    const itemRadius = computed(() => store.itemRadius);
    const columns = computed(() => store.columns);
    const rows = computed(() => store.rows);
    const XGap = computed(() => store.XGap);
    const YGap = computed(() => store.YGap);
    const color = computed(() => store.color);
    const lightColor = computed(() => store.lightColor);
    const lineColor = computed(() => store.lineColor);
    const changeNumber = computed(() => store.changeNumber);
    const back = computed(() => store.back);
    let circleData = ref([] as Array<ICircle>);
    onMounted(() => {
      circleData.value = generateRectArray(
        rows.value,
        columns.value
      ).flat();
      store.setCircleData(circleData.value);
    });
    watch([itemRadius,columns,rows, XGap,YGap,color,lightColor,changeNumber], () => {
        circleData.value = generateRectArray(rows.value,columns.value).flat();
        store.setCircleData(circleData.value);
      },{ deep: true }
    );
 
    function generateRectArray(rows, cols) {
      var rectArray = [] as Array<Array<ICircle>>;
      for (var i = 0; i < rows; i++) {
        var rowArray = [] as Array<ICircle>;
        for (var j = 0; j < cols; j++) {
          var x = 20 + j * ( XGap.value);
          var y = 20 + i * ( YGap.value);
          var rect = {
            x: x,
            y: y,
            radius: itemRadius.value,
            fill: color.value,
          };
          rowArray.push(rect);
        }
        rectArray.push(rowArray);
      }
      return rectArray;
    }
    let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    const points = computed(() => store.points) as ComputedRef<Array<number>>;
    const segment = computed(() => store.segment) as ComputedRef<Array<ISegment>>;
    const TextDatas = computed(() => store.textDatas) as ComputedRef<Array<ITextDatas>>;
    const operations = computed(() => store.operations) as any;
    // 撤销 操作
    watch([back], () => {
      if(operations.value.length > 0) {
        const len = operations.value.length
          const lastItem = operations.value[len-1]
          if(lastItem.length == 1){ // 只创建一个点
            console.log("11");
            
            if(lastItem[0].isexist){
              operations.value.splice(len-1,1)
              points.value.splice(0,points.value.length)
            }else {
              operations.value.splice(len-1,1)
              TextDatas.value.splice(TextDatas.value.length-1,1) // 判断是否为 已创建的点 不是则删除
              const x = lastItem[0].data.x -10
            const y = lastItem[0].data.y +25
            circleData.value.forEach((c) => {
              if(c.x == x && c.y == y) {
                c.fill = color.value;
              }
            })
              points.value.splice(0,points.value.length)
            }
          }else {// 创建一个点 和一条线
            console.log("22");
            if(lastItem[0].isexist){
              console.log(lastItem[0].data);
              
            //   const x = lastItem[0].data.x -10
            // const y = lastItem[0].data.y +25
            // circleData.value.forEach((c) => {
            //   if(c.x == x && c.y == y) {
            //     c.fill = color.value;
            //   }
            // })
            }else {
            TextDatas.value.splice(TextDatas.value.length-1,1) // 判断是否为 已创建的点 不是则删除
            const x = lastItem[0].data.x -10
            const y = lastItem[0].data.y +25
            circleData.value.forEach((c) => {
              if(c.x == x && c.y == y) {
                c.fill = color.value;
              }
            })
            }
            console.log("11",lastItem);
           
            points.value.push(lastItem[1].data[0],lastItem[1].data[1])
            segment.value.splice(segment.value.length-1,1)
            operations.value.splice(len-1,1)
          }
        // if(operations.value.length ==1) {
        //   store.reset()
        // }else {
        
          
        // }
      }else {
        message.error('没有可撤销的操作');
      }
     
   })
    let timeId = ref(0 as number | any);
    function selectItem(item) {
      const { x, y } = item;
      const op =[] as any
      circleData.value.forEach((c) => {
          if (c.x == x && c.y == y) {
            if( c.fill === color.value) {
              c.fill = lightColor.value;
            }else if(c.fill == lightColor.value) {
              c.fill = 'lightgreen';
              timeId.value = setTimeout(() => {
                c.fill = lightColor.value;
              }, 1000);
            }
         
            points.value.push(c.x, c.y);
            const text = alphabet[TextDatas.value.length];
            let textData = {
              x: c.x+10,
              y: c.y - 25,
              text: text,
              fontSize: 18,
              fontFamily: 'Calibri',
              fill: '#000',
              align: 'center',
            };
            if (TextDatas.value.length == 0) {
              TextDatas.value.push(textData);
              op.push({
                type: 'text',
                isexist: false,
                data: textData
              })
            } else {
              if (!isInTextDatas(textData)) {
                TextDatas.value.push(textData);
                op.push({
                type: 'text',
                isexist: false,
                data: textData
              })
              }else{
                op.push({
                type: 'text',
                isexist: true,
                data: textData
              })
              }
            }
          }
      });
      if (points.value.length == 4) {
          segment.value.push({
            points: [...points.value],
            stroke: lineColor.value,
            strokeWidth: 4,
            lineCap: 'round',
            lineJoin: 'round',
          });
          op.push({
                type: 'segment',
                data: [...points.value]
              })
          points.value.splice(0, 4);
      }
      operations.value.push(op)
      store.setPoints(JSON.parse(JSON.stringify(points.value)))
      store.setSegment(JSON.parse(JSON.stringify(segment.value)))
      store.setTextDatas(JSON.parse(JSON.stringify(TextDatas.value)))
      store.setOperations(JSON.parse(JSON.stringify(operations.value)))
      store.setCircleData(JSON.parse(JSON.stringify(circleData.value)))
     
      console.log("点",points.value);
      console.log("线段",segment.value);
      console.log("文字",TextDatas.value);
      console.log("操作过程",operations.value);
    }

    function isInTextDatas(value) {
      for (let i = 0; i <  TextDatas.value.length; i++) {
        const item =  TextDatas.value[i];
        if (item.x == value.x && item.y == value.y) {
         return true;
        }
      }
      return false;
    }
    return {
      selectItem,
      circleData,
      configKonva,
      segment,
      TextDatas,
    };
  },
});
</script>

<style scoped lang="less">
[data-control='pinboard2ix'] .container {
  box-sizing: border-box;
  user-select: none;
  width: 100%;
  height: 100%;
}
</style>
